<template>
  <div class="message-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2 class="page-title">
          <el-icon><ChatDotRound /></el-icon>
          我的消息
        </h2>
        <p class="page-subtitle">查看和管理您收到的所有消息</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="markAllAsRead" :disabled="!hasUnreadMessages">
          <el-icon><Check /></el-icon>
          全部标记已读
        </el-button>
        <el-button @click="refreshMessages">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card total-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Message /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ messageStats.total }}</div>
              <div class="stat-label">总消息数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card unread-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Bell /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ messageStats.unread }}</div>
              <div class="stat-label">未读消息</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card important-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ messageStats.important }}</div>
              <div class="stat-label">重要消息</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card today-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ messageStats.today }}</div>
              <div class="stat-label">今日消息</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索消息标题或内容"
            clearable
            style="width: 200px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="消息类型">
          <el-select
            v-model="searchForm.type"
            placeholder="选择消息类型"
            clearable
            style="width: 150px"
          >
            <el-option label="系统通知" value="system" />
            <el-option label="工作通知" value="work" />
            <el-option label="个人消息" value="personal" />
            <el-option label="公告消息" value="announcement" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="未读" value="unread" />
            <el-option label="已读" value="read" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 消息列表 -->
    <el-card class="message-list-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>消息列表</span>
          <div class="header-actions">
            <el-button type="danger" @click="batchDelete" :disabled="selectedMessages.length === 0">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="messageList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="标题" min-width="200">
          <template #default="{ row }">
            <div class="message-title">
              <el-icon v-if="!row.isRead" class="unread-dot"><CircleCheckFilled /></el-icon>
              <el-icon v-if="row.isImportant" class="important-icon"><Star /></el-icon>
              <span :class="{ 'unread-text': !row.isRead }">{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)" size="small">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sender" label="发送者" width="120" />
        <el-table-column prop="createTime" label="发送时间" width="180" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.isRead ? 'info' : 'warning'" size="small">
              {{ row.isRead ? '已读' : '未读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewMessage(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button
              :type="row.isRead ? 'warning' : 'success'"
              size="small"
              @click="toggleReadStatus(row)"
            >
              <el-icon><Check /></el-icon>
              {{ row.isRead ? '标记未读' : '标记已读' }}
            </el-button>
            <el-button type="danger" size="small" @click="deleteMessage(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="消息详情"
      width="600px"
      :before-close="handleCloseDetail"
    >
      <div v-if="currentMessage" class="message-detail">
        <div class="detail-header">
          <h3 class="detail-title">{{ currentMessage.title }}</h3>
          <div class="detail-meta">
            <span class="sender">发送者：{{ currentMessage.sender }}</span>
            <span class="time">时间：{{ currentMessage.createTime }}</span>
            <el-tag :type="getTypeTagType(currentMessage.type)" size="small">
              {{ getTypeLabel(currentMessage.type) }}
            </el-tag>
          </div>
        </div>
        <div class="detail-content">
          <p>{{ currentMessage.content }}</p>
        </div>
        <div
          v-if="currentMessage.attachments && currentMessage.attachments.length > 0"
          class="detail-attachments"
        >
          <h4>附件：</h4>
          <ul>
            <li v-for="attachment in currentMessage.attachments" :key="attachment.id">
              <el-link type="primary" @click="downloadAttachment(attachment)">
                <el-icon><Document /></el-icon>
                {{ attachment.name }}
              </el-link>
            </li>
          </ul>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="replyMessage">回复</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ChatDotRound,
  Check,
  Refresh,
  Message,
  Bell,
  Star,
  Calendar,
  Search,
  Delete,
  View,
  CircleCheckFilled,
  Document,
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)
const currentMessage = ref<any>(null)
const selectedMessages = ref<any[]>([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  type: '',
  status: '',
  dateRange: [],
})

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
})

// 消息统计数据
const messageStats = reactive({
  total: 0,
  unread: 0,
  important: 0,
  today: 0,
})

// 消息列表数据
const messageList = ref([
  {
    id: 'MSG001',
    title: '系统维护通知',
    content: '系统将于今晚22:00-24:00进行维护，期间可能影响正常使用，请提前做好准备。',
    type: 'system',
    sender: '系统管理员',
    createTime: '2024-12-01 10:30:00',
    isRead: false,
    isImportant: true,
    attachments: [],
  },
  {
    id: 'MSG002',
    title: '工作安排通知',
    content: '请各位同事注意，本周五下午将召开项目进度会议，请准时参加。',
    type: 'work',
    sender: '项目经理',
    createTime: '2024-12-01 09:15:00',
    isRead: true,
    isImportant: false,
    attachments: [{ id: 'ATT001', name: '会议议程.pdf' }],
  },
  {
    id: 'MSG003',
    title: '个人消息',
    content: '您的请假申请已通过审批，请及时查看。',
    type: 'personal',
    sender: '人事部',
    createTime: '2024-12-01 08:45:00',
    isRead: false,
    isImportant: false,
    attachments: [],
  },
  {
    id: 'MSG004',
    title: '公司公告',
    content: '关于调整工作时间的通知，从下周开始，工作时间调整为9:00-18:00。',
    type: 'announcement',
    sender: '行政部',
    createTime: '2024-11-30 16:20:00',
    isRead: true,
    isImportant: true,
    attachments: [],
  },
])

// 计算属性
const hasUnreadMessages = computed(() => {
  return messageList.value.some((msg) => !msg.isRead)
})

// 方法
const getTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    system: '系统通知',
    work: '工作通知',
    personal: '个人消息',
    announcement: '公告消息',
  }
  return typeMap[type] || type
}

const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    system: 'danger',
    work: 'primary',
    personal: 'success',
    announcement: 'warning',
  }
  return typeMap[type] || 'info'
}

const handleSearch = () => {
  loading.value = true
  // 模拟搜索
  setTimeout(() => {
    loading.value = false
    ElMessage.success('搜索完成')
  }, 1000)
}

const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    type: '',
    status: '',
    dateRange: [],
  })
  handleSearch()
}

const handleSelectionChange = (selection: any[]) => {
  selectedMessages.value = selection
}

const viewMessage = (message: any) => {
  currentMessage.value = message
  detailDialogVisible.value = true
  // 标记为已读
  if (!message.isRead) {
    message.isRead = true
    updateMessageStats()
  }
}

const toggleReadStatus = (message: any) => {
  message.isRead = !message.isRead
  updateMessageStats()
  ElMessage.success(message.isRead ? '已标记为已读' : '已标记为未读')
}

const deleteMessage = (message: any) => {
  ElMessageBox.confirm('确定要删除这条消息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const index = messageList.value.findIndex((msg) => msg.id === message.id)
    if (index > -1) {
      messageList.value.splice(index, 1)
      updateMessageStats()
      ElMessage.success('删除成功')
    }
  })
}

const batchDelete = () => {
  if (selectedMessages.value.length === 0) {
    ElMessage.warning('请选择要删除的消息')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedMessages.value.length} 条消息吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const ids = selectedMessages.value.map((msg) => msg.id)
    messageList.value = messageList.value.filter((msg) => !ids.includes(msg.id))
    selectedMessages.value = []
    updateMessageStats()
    ElMessage.success('批量删除成功')
  })
}

const markAllAsRead = () => {
  messageList.value.forEach((msg) => {
    msg.isRead = true
  })
  updateMessageStats()
  ElMessage.success('全部标记为已读')
}

const refreshMessages = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    updateMessageStats()
    ElMessage.success('刷新完成')
  }, 1000)
}

const handleCloseDetail = () => {
  detailDialogVisible.value = false
  currentMessage.value = null
}

const replyMessage = () => {
  ElMessage.info('回复功能开发中...')
}

const downloadAttachment = (attachment: any) => {
  ElMessage.info(`下载附件：${attachment.name}`)
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  handleSearch()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  handleSearch()
}

const updateMessageStats = () => {
  messageStats.total = messageList.value.length
  messageStats.unread = messageList.value.filter((msg) => !msg.isRead).length
  messageStats.important = messageList.value.filter((msg) => msg.isImportant).length
  messageStats.today = messageList.value.filter((msg) => {
    const today = new Date().toDateString()
    const msgDate = new Date(msg.createTime).toDateString()
    return today === msgDate
  }).length
}

// 生命周期
onMounted(() => {
  updateMessageStats()
})
</script>

<style scoped lang="less">
.message-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .header-content {
    .page-title {
      display: flex;
      align-items: center;
      gap: 10px;
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;

      .el-icon {
        font-size: 28px;
        color: #409eff;
      }
    }

    .page-subtitle {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }
}

.stats-row {
  margin-bottom: 20px;

  .stat-card {
    .stat-content {
      display: flex;
      align-items: center;
      gap: 15px;

      .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        color: white;
      }

      .stat-info {
        .stat-value {
          font-size: 24px;
          font-weight: 600;
          color: #303133;
          line-height: 1;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
          margin-top: 4px;
        }
      }
    }

    &.total-card .stat-icon {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    &.unread-card .stat-icon {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }

    &.important-card .stat-icon {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }

    &.today-card .stat-icon {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    }
  }
}

.search-card {
  margin-bottom: 20px;

  .search-form {
    margin: 0;
  }
}

.message-list-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .message-title {
    display: flex;
    align-items: center;
    gap: 8px;

    .unread-dot {
      color: #f56c6c;
      font-size: 12px;
    }

    .important-icon {
      color: #e6a23c;
      font-size: 14px;
    }

    .unread-text {
      font-weight: 600;
      color: #303133;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.message-detail {
  .detail-header {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;

    .detail-title {
      margin: 0 0 10px 0;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }

    .detail-meta {
      display: flex;
      align-items: center;
      gap: 15px;
      font-size: 14px;
      color: #909399;

      .sender,
      .time {
        display: flex;
        align-items: center;
        gap: 5px;
      }
    }
  }

  .detail-content {
    margin-bottom: 20px;
    line-height: 1.6;
    color: #606266;
  }

  .detail-attachments {
    h4 {
      margin: 0 0 10px 0;
      font-size: 14px;
      color: #303133;
    }

    ul {
      margin: 0;
      padding-left: 20px;

      li {
        margin-bottom: 5px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .message-container {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;

    .header-actions {
      width: 100%;
      justify-content: center;
    }
  }

  .stats-row {
    .el-col {
      margin-bottom: 10px;
    }
  }

  .search-form {
    .el-form-item {
      margin-bottom: 10px;
    }
  }
}
</style>
